package com.itheima.putige.putige.controller;

import com.itheima.putige.putige.common.CustomException;
import com.itheima.putige.putige.common.R;
import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.UUID;

/**
 * Copyright (C), 2021-2022
 * Author: 16372
 * Date: 2022/3/1 19:43
 * FileName: CommonController
 * Description: 文件的上传与下载
 */
@RestController
@RequestMapping("/common")
@Slf4j
public class CommonController {
    @Value("${reggie.path}")
    private String basePath;

    @PostMapping("/upload")
    public R<String> upload(MultipartFile file){
        //file将临时文件,将其转存到指定位置
        log.info(file.toString());
        //获取原始文件名,和后缀名
        String originalFilename = file.getOriginalFilename();//abc.jpg
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));

        //生成新的文件名
        String fileName = "lstp_" + UUID.randomUUID().toString() + suffix;

        //创建一个目录对象
        File dir = new File(basePath);
        //判断当前目录是否存在
        if(!dir.exists()){
            //目录不存在，需要创建
            dir.mkdirs();
        }

        try {
            //将临时文件转存到指定位置
            file.transferTo(new File(basePath+fileName));
            log.info("本地保存成功,路径名:{}<====================================================",basePath + fileName);
            return R.success(fileName);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return R.error("图片保存失败");
    }

    /**
     * 文件下载
     * @param name 文件路径名
     * @param response 前端文件载体
     */
    @GetMapping("/download")
    public void download(String name, HttpServletResponse response){
        try {
            InputStream inputStream = null;
            if (name.contains("lstp_")){
                inputStream = new FileInputStream(new File(basePath + name));
                log.info("本地图片{}加载成功<===========================================",basePath + name);
            }else {
                String fileUrl = "http://" + name;
                //使用url替代获取然后转换成流即可
                URL url = new URL(fileUrl);
                inputStream = url.openStream();
                log.info("服务器图片{}加载成功<===========================================",fileUrl);
            }
            //输出流，通过输出流将文件写回浏览器
            ServletOutputStream outputStream = response.getOutputStream();

            response.setContentType("image/jpeg");

            IOUtils.copy(inputStream,outputStream);
            //关闭资源
            outputStream.close();
            inputStream.close();
        } catch (Exception e) {
            System.out.println("资源不存在");
        }
    }
}
